package com.jt.service;

import com.jt.vo.ImageVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


@Service
@PropertySource("classpath:properties/image.properties")
public class FileServiceImpl implements FileService{

    @Value("${image.localDirPath}")
    private String localDirPath;    //="E:/TCGB_Three/TOOLS/images";
    @Value("${image.urlPath}")
    private String urlPath;         //="http://image.jt.com";

    /**
     * 文件上传策略:
     *      1.图片类型的校验    1.正则表达式.. 2.???
     *      2.校验文件是否为木马   木马.exe.jpg 宽度/高度
     *      3.将文件分目录存储    1.hash asdfsdfa 2.时间
     *      4.防止文件重名  uuid当做名称
     * @param uploadFile
     * @return
     */
    @Override
    public ImageVO uploadFile(MultipartFile uploadFile) {
        String originalFilename = uploadFile.getOriginalFilename();//获取传入的文件名
        originalFilename = originalFilename.toLowerCase();//全小写

        //图片格式是计算机存储图片的格式，常见的存储的格式有
        //bmp,jpg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,
        // pcd,dxf,ufo,eps,ai,raw,WMF,webp,avif等
        if (!originalFilename.matches("^.+\\.(jpg|png|gif)$")){//根据正则表达式判断文件格式是否符合图片的格式
            return ImageVO.fail();
        }

        try {
            //通过IO流获取输入的流
            BufferedImage read = ImageIO.read(uploadFile.getInputStream());
//            获取文件长宽
            int height = read.getHeight();
            int width = read.getWidth();
//            判断文件是否有长宽
            if (height==0||width==0){
                return ImageVO.fail();
            }

            String dateDirPath = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
            String dirPath=localDirPath+dateDirPath;//生成动态文件路径
            File file = new File(dirPath);          //创建file对象
            if (!file.exists()){
                file.mkdirs();
            }

            String uuid= UUID.randomUUID().toString().replace("-","");
            int index = originalFilename.lastIndexOf(".");
            String fileType = originalFilename.substring(index);
            String realFile = uuid + fileType;
            File imageFile = new File(dirPath+realFile);
            uploadFile.transferTo(imageFile);

            String url=urlPath+dateDirPath+realFile;
            return ImageVO.success(url,width,height);

        } catch (IOException e) {
            e.printStackTrace();
            return ImageVO.fail();
        }
    }
}










